import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

axios.get('../static/goodsData.json')
  .then(function(res){
    state._goods = res.data.data;
  }).catch(function(err){
  console.log(err)
})

const state = {
  _goods: [],
  _goodsInfo: [],
  faker: false,
}

const mutations = {
  increment (state,id) {
    if(state._goods[id].surplus > 0){
      state._goods[id].surplus -= 1;
      state._goods[id].num += 1;

      state._goodsInfo = [];

      state._goods.map(({ id,title,introduce,price, num }) => {
        if(num > 0){
        var obj = {
          "id": id,
          "title": title,
          "introduce": introduce,
          "price":price,
          "num": num,
          "toallPrice": num * price,
        };
        state._goodsInfo.push(obj);
      }
    })

    }
  },
  decrement (state,id) {
    if(state._goods[id].num > 0){
      state._goods[id].surplus += 1;
      state._goods[id].num -= 1;

      state._goodsInfo.forEach((item,index,arr) => {
        if(item.id == id+1){
          if(item.num > 1){
            item.num -= 1;
            item.toallPrice = item.num * item.price;
          }else{
            arr.splice(index,1)
          }
        }
      })
    }
  },
}

const actions = {
  decrement: ({ commit },id) => commit('decrement',parseInt(id)),
  increment: ({ commit },id) => commit('increment',parseInt(id)),
  reqAxios (context)
  {
    state.faker = true;
    axios.get('../static/shopData.json')
      .then(function(res){
       // console.log(res.data.data)
      state._goods = [...state._goods,...res.data.data];
      setTimeout(()=>{
        state.faker = false;
      },1000)
    }).catch(function(err){
      console.log(err)
    })
  },
}

const getters = {
  getGoods: (state) => state._goods,
  getPrice: (state) => {
    var allPrice = 0.00;
    state._goods.map(({ id,title,price, num }) => {
      allPrice += parseFloat(price*num);
    })
    return allPrice.toFixed(1)
    },
  getInfo: (state) => state._goodsInfo,
  getFaker: (state) => state.faker
}

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})
